<script setup lang="ts">
import { ref, useTemplateRef, onActivated, onDeactivated } from 'vue'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
import { useGsapContext } from '@/hooks'
import { useScrollGroup } from '@/hooks/reno14-pro.ts'

withDefaults(
  defineProps<{
    videoSrc: string
    autoplay?: boolean
  }>(),
  {
    autoplay: false,
  },
)

const { scrollGroup } = useScrollGroup()

useGsapContext(() => {
  if (!videoRef.value) {
    return
  }

  ScrollTrigger.create({
    trigger: videoRef.value,
    start: 'top bottom',
    end: 'bottom top',
    onToggle: async (self) => {
      if (self.isActive) {
        await videoPlay()
      } else {
        videoStop()
      }
    },
    invalidateOnRefresh: true,
    ...scrollGroup,
  })
})

const videoRef = useTemplateRef<HTMLVideoElement | null>('videoRef')
const videoPlay = async () => {
  if (!videoRef.value) {
    return
  }

  await videoRef.value.play().catch()
}
const videoStop = () => {
  if (!videoRef.value) {
    return
  }

  videoRef.value.pause()
  videoRef.value.currentTime = 0
}

const showReply = ref(false)

onActivated(async () => {
  await videoPlay()
})
onDeactivated(videoStop)
</script>

<template>
  <div
    class="py-[5.5rem] relative bg-white max-sm:rounded-sm sm:py-[clamp(4.375rem,3.2888rem+2.6738vw,5rem)] lg:py-[clamp(5rem,-4rem+14.0625vw,9.5rem)]"
  >
    <div class="relative w-[78%] aspect-[311/147] mx-auto sm:w-[90%]">
      <picture class="relative z-1">
        <img
          class="w-full h-full"
          src="@/views/product/reno14-pro/image/5/images-game-frame-1.png.webp"
          loading="lazy"
          alt=""
        />
      </picture>

      <video
        ref="videoRef"
        class="w-full h-full absolute top-0 grid rounded-3xl overflow-hidden lg:rounded-[clamp(2rem,0rem+3.125vw,3rem)]"
        muted
        @play="showReply = false"
        @ended="showReply = true"
        :autoplay
        src="@/views/product/reno14-pro/image/5/videos-game-live_800.mp4"
      ></video>
    </div>

    <svg
      v-show="showReply"
      @click="videoPlay"
      class="w-[2rem] aspect-square absolute bottom-[8%] left-0 right-0 mx-auto"
    >
      <use href="#icon-replay" />
    </svg>
  </div>
</template>
